function template
<string>

std::operator>> (basic_string)

template <class charT, class traits, class Alloc>
  basic_istream<charT,traits>& operator>> (basic_istream<charT,traits>& is,
                                           basic_string<charT,traits,Alloc>& str);
Extract string from stream
Extracts a string from the input stream is, storing the sequence in str, which is overwritten (the previous value of str is replaced).

This function overloads operator>> to behave as described in basic_istream::operator>> for c-strings, but applied to basic_string objects.

Each extracted character is appended to the basic_string as if its member push_back was called.

Notice that the basic_istream extraction operations use whitespaces as separators; Therefore, this operation will only extract what can be considered a word from the stream. To extract entire lines of text, see the basic_string overload of global function getline.

Parameters

is
basic_istream object from which characters are extracted.
str
basic_string object where the extracted content is stored.

Return Value

The same as parameter is.

A call to this function may set any of the internal state flags of is if:

flagerror
eofbitThe end of the source of characters is reached during its operations.
failbitThe input obtained could not be interpreted as a valid textual representation of an object of this type.
In this case, distr preserves the parameters and internal data it had before the call.
Notice that some eofbit cases will also set failbit.
badbitAn error other than the above happened.
(see ios_base::iostate for more info on these)

Additionally, in any of these cases, if the appropriate flag has been set with is's member function basic_ios::exceptions, an exception of type ios_base::failure is thrown.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// extract to string
#include <iostream>
#include <string>

main ()
{
  std::string name;

  std::cout << "Please, enter your name: ";
  std::cin >> name;
  std::cout << "Hello, " << name << "!\n";

  return 0;
}


Complexity

Unspecified, but generally linear in the resulting length of str.

Iterator validity

Any iterators, pointers and references related to str may be invalidated.

Data races

Both objects, is and str, are modified.

Exception safety

Basic guarantee: if an exception is thrown, both is and str end up in a valid state.

See also